<template>
    <div class="body">
    <div class="box">
        <h3>拖动下方滑块完成拼图</h3>
        <div ref="bgImgRef" class="img-box">
            <img class="bg" src="../assets/hycdn.jpeg" alt="">
            <img class="hd" 
            src="../assets/hycdn.png" 
            :style="{ left: data.left + 'px',top:data.top+'px'}" 
            alt="">
        </div>
        
        <div class="btn-box">
            <div ref="btnRef" 
            class="btn"  
            @mousedown="btnMousedown" 
            :style="{ left: data.left + 'px'}"
            >
            |||</div>
        </div>
    </div>
    <div class="signature"><p>五十海里外的星空</p></div>
</div>
</template>

<script setup>
import { reactive, onMounted, toRefs } from 'vue';
// defineProps返回值是父元素的属性
let $props = defineProps({
    top: {
        type: Number,
        default: 45,
    }
});
let $emit = defineEmits(['getPosition']);
// let bntRef = ref(null)
const data = reactive({
    left: 0,
    top: $props.top,
    btnLeft: 0,

    // 空对像
    btnRef: null,
    offsetLeft:0,
    bgImgRef:null,
});
// let btnRef = ref(null);
const { btnRef,bgImgRef } = toRefs(data);//解构
onMounted(() => {
    data.offsetLeft = data.bgImgRef.offsetLeft;
    // data.offsetLeft = data.btnRef.offsetLeft;
    // console.log("onMounted");
    document.body.addEventListener("mouseup", btnMouseup);
})
//鼠标按下
var btnMousedown = (e) => {
    // console.log(e);
    // layerX: 35  layerY: 16 pageX: 57  pageY: 508  screenX: 141  screenY: 663
    // 计算出鼠标按下的位置 pageX - btn距离窗口的位置 = 鼠标点击位置距离btn的边距
    data.btnLeft = e.pageX - data.btnRef.offsetLeft;
    // console.log(data.btnLeft);
    document.body.addEventListener("mousemove", btnMousemove);
}
//滑动时只要求鼠标没有松开
var btnMousemove = (e) => {
    console.log(e);
    console.log("滑动",e);
    // left = 鼠标的位置pageX - data.btnRef.offsetLeft - data.btnLeft
    // let x = e.pageX - data.btnRef.offsetLeft - data.btnLeft;
    let x = e.pageX - data.offsetLeft - data.btnLeft;
    if (x <= 0) x = 0;
    else if (x >= 285) x = 285;
    data.left = x;
    console.log(x);
}
//松开
var btnMouseup = (e) => {
    // console.log("a",data.left);
    $emit("getPosition",data.left);
    document.body.removeEventListener("mousemove", btnMousemove);
}
</script>

<!-- <style lang="scss" scoped>

</style> -->
<style scoped>
@import '../assets/imgcheck.css';
</style>